#include<vector>
#include<unordered_map>
using std::vector;
using std::unordered_map;



struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};


class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        unordered_map<int, int> table;
        for (int i = 0; i < inorder.size(); i++) {
            table[inorder[i]] = i;
        }

        return subTree(preorder, inorder, 0, preorder.size(), 0, preorder.size(), table);
    }

    TreeNode* subTree(
        vector<int>& preorder,
        vector<int>& inorder,
        int startPre,
        int endPre,
        int startIn,
        int endIn,
        unordered_map<int, int>& table) {
            if (endPre == startPre) return nullptr;
            TreeNode* root = new TreeNode(preorder[startPre]);
            int splitIdx = table[preorder[startPre]];
            int n = endPre - startPre;
            int nl = splitIdx - startIn;
            root->left = subTree(preorder, inorder, startPre+1, startPre+nl+1, startIn, splitIdx, table);
            root->right = subTree(preorder, inorder, startPre+nl+1, endPre, splitIdx+1, endIn, table);
        return root;
    }
};